<template>
  <PageWrapper>
    <BasicTable
      @register="registerTable"
      :rowSelection="
        checkboxShow
          ? {
              type: 'checkbox',
              columnWidth: 44,
              selectedRowKeys: checkedDelKeys,
              onChange: onSelectChange,
              getCheckboxProps: onGetCheckboxProps
            }
          : null
      "
    >
      <template #tableTitle>
        <a-space :size="12">
          <a-button v-auth="permissionCodeMap.packageAdd" type="primary" @click="operatePackage(operateActionType.ADD)"
            >新增套餐</a-button
          >
          <a-button v-auth="permissionCodeMap.packageDel" :disabled="!checkedDelKeys.length" danger @click="operateDel"
            >批量删除</a-button
          >
        </a-space>
      </template>

      <template #bodyCell="{ column, record, text }">
        <template v-if="column.dataIndex === 'paymentMethod'">
          <span v-if="record.paymentMethod == 1">线上支付</span>
          <span v-else-if="record.paymentMethod == 2">联系客服</span>
        </template>
        <template v-else-if="column.dataIndex === 'orderCount'">
          <span>{{ record.orderCount || 0 }}个</span>
        </template>
        <template v-else-if="column.dataIndex === 'unitPrice'">
          <span>{{ formatMoney(record.unitPrice) }}</span>
        </template>
        <template v-else-if="column.dataIndex === 'packageStatus'">
          <span class="global-active-status" v-if="record.packageStatus == '1'">已上架</span>
          <span class="global-stop-status" v-else-if="record.packageStatus == '2'">已下架</span>
        </template>
        <template v-else-if="column.dataIndex === 'operate'">
          <a-button
            type="link"
            v-auth="permissionCodeMap.packageView"
            class="g-operate-btn"
            @click="operatePackage(operateActionType.VIEW, record)"
            >查看</a-button
          >
          <a-button
            type="link"
            v-if="record.userId !== currentUserId"
            v-auth="permissionCodeMap.packageEdit"
            class="g-operate-btn"
            @click="operatePackage(operateActionType.EDIT, record)"
            >编辑</a-button
          >
          <a-button
            type="link"
            v-if="record.userId !== currentUserId"
            v-auth="permissionCodeMap.packageEdit"
            class="g-operate-btn"
            @click="operateStatus(record)"
            >{{ record.packageStatus == '1' ? '下架' : '上架' }}</a-button
          >
        </template>
      </template>
    </BasicTable>
    <PackageAdd @register="packageAddRegister" @operateSuccess="operateSuccess" />
  </PageWrapper>
</template>

<script lang="ts" setup>
import { reactive, ref, computed, unref, watch, createVNode, onMounted } from 'vue'
import PageWrapper from '@/components/PageWrapper/index.vue'
import { BasicTable, useTable } from '@/components/Table'
import { getPackageBasicColumns, getSearchFormConfig } from './dataSource'
import { useDrawer } from '@/components/Drawer'
import { useModal } from '@/components/Modal'
import PackageAdd from './components/PackageAdd.vue'
import { userStore } from '@/store/modules/user'
import { permissionCodeMap } from '@/utils/permissionCodeMap'
import { operateActionType, operateTxtType, constantMap } from '@/types/enum'
import { PackageRecord } from '@/types/goods'
import { message, Modal } from 'ant-design-vue'
import { ExclamationCircleFilled } from '@ant-design/icons-vue'
import { formatMoney } from '@/utils/index'
import { toEleTreeData } from '@/utils'
import api from '@/api'
const { packageQueryPage, packageDel, packageModify } = api

const userModule = userStore()

const currentUserId = computed(() => userModule.userInfo?.userId)
const checkboxShow = computed(() => userModule.permissionActionList.includes(permissionCodeMap.packageDel))

const [registerTable, { reload, setPagination }] = useTable({
  api: packageQueryPage,
  columns: getPackageBasicColumns(),
  useSearchForm: true,
  formConfig: getSearchFormConfig(),
  showIndexColumn: true,
  rowKey: 'id',
  scroll: { y: constantMap.tableYHeight, x: constantMap.tableXWidth }
})

const [packageAddRegister, { openDrawer: PackageAddOpenDrawer, setDrawerProps }] = useDrawer()

const checkedDelKeys = ref<Array<string | number>>([])

const onSelectChange = (selectedRowKeys: (string | number)[], selectedRow: PackageRecord[]) => {
  checkedDelKeys.value = selectedRowKeys
}
const operateSuccess = () => {
  setPagination({
    current: 1
  })
  reload()
}

// 禁止删除已上架并已售数量大于0的套餐
const onGetCheckboxProps = (record: PackageRecord) => {
  let orderCount = record.orderCount || 0
  return {
    disabled: record.packageStatus == '1' || orderCount > 0
  }
}
// 批量删除
const operateDel = () => {
  Modal.confirm({
    title: '确定批量删除所选套餐？',
    centered: true,
    icon: createVNode(ExclamationCircleFilled),
    content: `删除后数据不可恢复`,
    autoFocusButton: null,
    class: 'modal-confirm-box',
    async onOk() {
      await packageDel({
        idSet: checkedDelKeys.value
      })
      message.success(`删除成功`)
      operateSuccess()
    },
    onCancel() {}
  })
}
// 上架下架状态修改
const operateStatus = (record: PackageRecord) => {
  Modal.confirm({
    title: '提示',
    centered: true,
    icon: createVNode(ExclamationCircleFilled),
    content: record.packageStatus == '1' ? '确定下架所选套餐？' : '确定上架所选套餐？',
    autoFocusButton: null,
    class: 'modal-confirm-box',
    async onOk() {
      await packageModify({
        id: record.id,
        packageStatus: record.packageStatus == '1' ? '2' : '1'
      })
      message.success(`修改成功`)
      operateSuccess()
    },
    onCancel() {}
  })
}
const operatePackage = (type: OperateType, record?: PackageRecord) => {
  setDrawerProps({
    title: operateTxtType[type] + '套餐',
    showOkBtn: type !== operateActionType.VIEW,
    cancelText: type === operateActionType.VIEW ? '关闭' : '取消'
  })
  PackageAddOpenDrawer(true, {
    type,
    record
  })
}
</script>

<style lang="less" scoped></style>
